<?php

namespace app\admin\controller\video;

use app\common\controller\Backend;
use Aws\AwsService;
use Dir;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Queue;
use think\queue\Job;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class Video extends Backend
{

    protected $relationSearch = true;


    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Video');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法

        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $map = [];
            if (input('pid')) {
                $map['video.pid'] = input('pid');
            }
            $total = $this->model
                ->with('videolist')
                ->where($where)
                ->where($map)
//                ->order('video.name', 'asc')
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->with('videolist')
                ->where($where)
                ->where($map)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as &$item) {
                $item['img'] = $item['img'];
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL, $pid = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        if ($row['lx'] == 1) {
            $lx = 'video/mp4';
            $lxname = '视频';
        } elseif ($row['lx'] == 2) {
            $lx = 'audio/mpeg';
            $lxname = '音频';
        } elseif ($row['lx'] == 3) {
            $lx = 'wenz';
            $lxname = '文章';
        } else {
            $lx = '';
            $lxname = '';
        }
        $this->view->assign('lx', $lx);
        $this->view->assign('lxname', $lxname);


        $Videolist = model('Videolist')->get($pid);
        $this->view->assign('Videolist', $Videolist);
        return parent::edit($ids);
    }

    public function getsignature()
    {

        $site = config('site');
        $secret_id = $site['txydbapi']['secret_id'];
        $secret_key = $site['txydbapi']['secret_key'];

        // 确定签名的当前时间和失效时间
        $current = time();
        $expired = $current + 86400;  // 签名有效期：1天

        // 向参数列表填入参数
        $arg_list = array(
            "secretId" => $secret_id,
            "currentTimeStamp" => $current,
            "expireTime" => $expired,
            "random" => rand());

        // 计算签名
        $original = http_build_query($arg_list);
        $signature = base64_encode(hash_hmac('SHA1', $original, $secret_key, true) . $original);
        echo json_encode(['code' => '1', 'signature' => $signature]);
    }

    public function add($pid = NULL)
    {

        $Videolist = model('Videolist')->get($pid);
        if ($Videolist['lx'] == 1) {
            $lx = 'video/mp4';
            $lxname = '视频';
        } elseif ($Videolist['lx'] == 2) {
            $lx = 'audio/mp3';
            $lxname = '音频';
        } elseif ($Videolist['lx'] == 3) {
            $lx = 'wenz';
            $lxname = '文章';
        } else {
            $lx = '';
            $lxname = '';
        }
        $this->view->assign('lx', $lx);
        $this->view->assign('lxname', $lxname);
        $this->view->assign('Videolist', $Videolist);
        if ($Videolist) {
            return parent::add();
        } else {
            echo '请到视频管理里添加';
        }

    }

    public function addmore($pid = NULL)
    {
        $Videolist = model('Videolist')->get($pid);
            if ($Videolist['lx'] == 1) {
                $lx = 'video/mp4';
                $lxname = '视频';
                $type='video';
            } elseif ($Videolist['lx'] == 2) {
                $lx = 'audio/mp3';
                $lxname = '音频';
                $type='audio';
            } elseif ($Videolist['lx'] == 3) {
                $lx = 'wenz';
                $lxname = '文章';
                $type='txt';
            } else {
                $lx = '';
                $lxname = '';
                $type='file';
            }
            $this->view->assign('lx', $lx);
            $this->view->assign('lxname',$lxname);
            $this->view->assign('Videolist',$Videolist);
//            $dir = dirname($_SERVER['SCRIPT_FILENAME']) . '/uploads/video/'.$pid; // 指定目录路径
//            $files = $this->fileList($dir);
            $AwsService = new AwsService();
            $files = $AwsService->getFilesByPath($pid);
            $hasin = \app\common\model\Video::where('pid',$pid)->whereIn('videourl',$files)->field('videourl')->select();
            $has=[];
            foreach ($hasin as $v) {
                $has[]=$v['videourl'];
            }
            if($hasin)$files = array_diff($files, $has);
             sort($files);
            $this->view->assign('filelist',$files);
        if ($Videolist) {
                $params = $this->request->post("row/a");
                $max_weigh = model('Video')->where('pid',$pid)->max("weigh");
                if(!empty($params)) {
                    $newData['pid'] = $params['pid'];
                    $newData['img'] = $params['img'];
                    $newData['price'] = $params['price'];
                    $newData['vipprice'] = $params['vipprice'];
                    $newData['weigh'] = $max_weigh;
                    $newData['lx'] = $params['lx'];
                    $newData['info'] = $params['info'];
                    $newData['status'] = 'Normal';
                    $newData['ishot'] = 0;
                    $newData['plays'] = 0;
                    $newData['playeds'] = 0;
                    $newData['createtime'] = time();
                    Db::startTrans();
                    try {
                    $appends = [];
                        foreach ($params['videourl'] as $key => $file) {
                            $file_name = getPathName($file);
                            $newData['weigh'] = $newData['weigh'] + 1;
                            $newData['name'] =$file_name;
                            $jnumber = filter_var($file_name, FILTER_SANITIZE_NUMBER_INT);
                            $newData['weigh'] = (int)$jnumber;

                            //改文件名
                            //$uniqid =uniqid();
                            //$AwsService->renameS3File($file,$name,$uniqid);
                            //$file = str_replace($name,$uniqid,$file);
                            $newData['videourl'] = $file;
                            //$newid = model('Video')->insertGetId($newData);
                            //$this->addJob($newid,$file);
                            $appends[]=$newData;
                        }
                        model('Video')->insertAll($appends);
                        Db::commit();
                        return $this->success();
                    } catch (ValidateException $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    } catch (PDOException $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    } catch (Exception $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    }
                }
                return $this->view->fetch();
        } else {
            echo '请到视频管理里添加';
        }
    }

    public function fileList($directoryPath){
        $files = scandir($directoryPath);
// 过滤掉 '.' 和 '..'
        $files = array_diff($files, ['.', '..']);
// 打印文件列表
        $list = [];
        foreach ($files as $file) {
            $list[]=[
                'path'=>$directoryPath.'/'.$file,
                'name'=>$file
                ];
        }
        return $list;
    }


    /**
     * 生成上传任务
     * @param $data_id
     * @param $path
     * @return void
     */
    public function addJob($data_id, $path){
        // 1.当前任务将由哪个类来负责处理。
        //   当轮到该任务时，系统将生成一个该类的实例，并调用其 fire 方法
        $jobHandlerClassName  = 'app\api\controller\DoJob';
        // 2.当前任务归属的队列名称，如果为新队列，会自动创建
        $jobQueueName  = "JobQueue";

        trace("队列开始:".__FUNCTION__." ". time());
        // 3.当前任务所需的业务数据 . 不能为 resource 类型，其他类型最终将转化为json形式的字符串
        //   ( jobData 为对象时，存储其public属性的键值对 )
        $jobData = [ 'type'=>1, 'data_id' => $data_id,'path'=>$path,'ts' => time()] ;
        // 4.将该任务推送到消息队列，等待对应的消费者去执行
        $isPushed = Queue::push( $jobHandlerClassName , $jobData , $jobQueueName );

        if( $isPushed !== false ){
            return ;
        }else{
            return ;
        }
    }

}
